package com.chris.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DbConnection {
    private static DataSource druidDataSource;
    private static final ThreadLocal<Connection> local = new ThreadLocal<>();
    static {
        InputStream in = DbConnection.class.getResourceAsStream("/dbConfig.properties");
        Properties properties = new Properties();
        try {
            properties.load(in);
        }catch (IOException e){
            e.printStackTrace();
        }
        try {
            druidDataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
        Connection connection = local.get();
        try {
            if(connection==null){
                connection = druidDataSource.getConnection();
                local.set(connection);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }
    public static void begin(){
        Connection connect = getConnection();
        try {
            connect.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void commit(){
        Connection connect = null;
        try {
            connect = getConnection();
            connect.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeConnection(connect);
        }
    }
    public static void rollBack(){
        Connection connect= null;
        try {
            connect = getConnection();
            connect.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeConnection(connect);
        }
    }
    private static void closeConnection(Connection connection){
        if(connection!=null) {
            try {
                local.remove();
                connection.close();
            } catch (SQLException e) {
                local.remove();
                e.printStackTrace();
            }
        }
    }

    public  static void endServe(){
        Connection connection = getConnection();
        if(connection!=null) {
            try {
                local.remove();
                connection.close();
            } catch (SQLException e) {
                local.remove();
                e.printStackTrace();
            }
        }
    }
}
